package com.qst.order.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.qst.order.domain.Order;
import com.qst.order.domain.VO.ProductRankVO;
import com.qst.order.domain.VO.StatusDistributionVO;
import com.qst.order.domain.VO.SummaryVO;
import com.qst.order.domain.VO.TrendVO;
import com.qst.order.mapper.OrderItemMapper;
import com.qst.order.mapper.OrderMapper;
import com.qst.order.mapper.ProductMapper;
import com.qst.order.service.StatisticsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class StatisticsServiceImpl implements StatisticsService {

    private final OrderMapper orderMapper;
    private final ProductMapper productMapper;

    @Override
    public SummaryVO getSummaryStatistics() {
        LocalDate today = LocalDate.now();
        LocalDate firstDayOfMonth = today.withDayOfMonth(1);

        // 今日订单数 & 变化率
        Integer todayOrderCount = orderMapper.countTodayOrders(today);
        Integer yesterdayOrderCount = orderMapper.countTodayOrders(today.minusDays(1));
        Integer todayOrderChange = calculateChangeRate(todayOrderCount, yesterdayOrderCount);

        // 今日销售额 & 变化率
        BigDecimal todaySalesAmount = orderMapper.sumTodaySales(today);
        BigDecimal yesterdaySalesAmount = orderMapper.sumTodaySales(today.minusDays(1));
        Integer todaySalesChange = calculateChangeRate(todaySalesAmount, yesterdaySalesAmount);

        // 本月订单数 & 变化率
        Integer monthOrderCount = countMonthOrders(firstDayOfMonth, today);
        Integer lastMonthOrderCount = countMonthOrders(firstDayOfMonth.minusMonths(1), firstDayOfMonth.minusDays(1));
        Integer monthOrderChange = calculateChangeRate(monthOrderCount, lastMonthOrderCount);

        // 本月销售额 & 变化率
        BigDecimal monthSalesAmount = sumMonthSales(firstDayOfMonth, today);
        BigDecimal lastMonthSalesAmount = sumMonthSales(firstDayOfMonth.minusMonths(1), firstDayOfMonth.minusDays(1));
        Integer monthSalesChange = calculateChangeRate(monthSalesAmount, lastMonthSalesAmount);

        SummaryVO vo = new SummaryVO();
        vo.setTodayOrderCount(todayOrderCount);
        vo.setTodayOrderChange(todayOrderChange);
        vo.setTodaySalesAmount(todaySalesAmount);
        vo.setTodaySalesChange(todaySalesChange);
        vo.setMonthOrderCount(monthOrderCount);
        vo.setMonthOrderChange(monthOrderChange);
        vo.setMonthSalesAmount(monthSalesAmount);
        vo.setMonthSalesChange(monthSalesChange);
        return vo;
    }

    // 计算变化率（工具方法）
    // 计算变化率（工具方法）
    private Integer calculateChangeRate(Number current, Number previous) {
        // 处理 current 为 null 的情况
        if (current == null) {
            return previous == null ? 0 : -100;
        }

        // 处理 previous 为 null 或 0 的情况
        if (previous == null || previous.doubleValue() == 0) {
            return current.doubleValue() > 0 ? 100 : 0;
        }

        // 计算变化率
        double rate = ((current.doubleValue() - previous.doubleValue()) / previous.doubleValue()) * 100;
        return (int) Math.round(rate);
    }
    // 统计指定月份订单数
    // 统计指定月份订单数
    private Integer countMonthOrders(LocalDate start, LocalDate end) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.between("create_time", start.atStartOfDay(), end.atTime(23, 59, 59));

        Long count = orderMapper.selectCount(wrapper);
        // 确保不会返回 null
        return count != null ? count.intValue() : 0;
    }

    // 统计指定月份销售额
    // 统计指定月份销售额
    private BigDecimal sumMonthSales(LocalDate start, LocalDate end) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.between("create_time", start.atStartOfDay(), end.atTime(23, 59, 59));
        wrapper.select("SUM(total_price) AS total"); // 注意这里使用的是 total_price 而不是 total_amount

        List<Map<String, Object>> list = orderMapper.selectMaps(wrapper);

        // 关键修复：检查列表是否为空或第一个元素是否为 null
        if (list == null || list.isEmpty() || list.get(0) == null) {
            return BigDecimal.ZERO;
        }

        Object totalObj = list.get(0).get("total");
        // 处理 total 为 null 的情况（当没有数据时）
        if (totalObj == null) {
            return BigDecimal.ZERO;
        }

        // 处理不同数据类型的转换
        if (totalObj instanceof BigDecimal) {
            return (BigDecimal) totalObj;
        } else if (totalObj instanceof Double) {
            return BigDecimal.valueOf((Double) totalObj);
        } else if (totalObj instanceof Long) {
            return BigDecimal.valueOf((Long) totalObj);
        } else {
            return new BigDecimal(totalObj.toString());
        }
    }

    @Override
    public List<TrendVO> getOrderTrend(LocalDate startDate, LocalDate endDate) {
        LocalDate actualEndDate = endDate.plusDays(1);// 将结束日期加 1 天，以包含结束日期
        List<Map<String, Object>> list = orderMapper.getOrderTrend(startDate, actualEndDate);
        return list.stream().map(map -> {
            TrendVO vo = new TrendVO();
            vo.setDate(map.get("date").toString());
            vo.setValue(Integer.parseInt(map.get("count").toString()));
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<TrendVO> getSalesTrend(LocalDate startDate, LocalDate endDate) {
        List<Map<String, Object>> list = orderMapper.getSalesTrend(startDate, endDate);
        return list.stream().map(map -> {
            TrendVO vo = new TrendVO();
            vo.setDate(map.get("date").toString());
            vo.setValue(((BigDecimal) map.get("amount")).doubleValue());
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<StatusDistributionVO> getOrderStatusDistribution() {
        List<Map<String, Object>> list = orderMapper.getStatusDistribution();
        return list.stream().map(map -> {
           log.warn("map: {}", map);
            StatusDistributionVO vo = new StatusDistributionVO();
            vo.setStatusName(map.get("status_name").toString());
            vo.setCount(Integer.parseInt(map.get("count").toString()));
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ProductRankVO> getProductRank(String type) {
        // 调用 Mapper 获取原始统计数据
        List<Map<String, Object>> list = productMapper.getProductRank(type);

        // 转换为 ProductRankVO 列表（处理空值）
        return list.stream().map(map -> {
            ProductRankVO vo = new ProductRankVO();
            // 商品名称（默认空字符串避免 null）
            vo.setProductName(map.get("product_name") != null ? map.get("product_name").toString() : "未知商品");
            // 销量（默认0避免 null）
            vo.setQuantity(map.get("quantity") != null ? Integer.parseInt(map.get("quantity").toString()) : 0);
            // 销售额（默认0避免 null）
            vo.setAmount(map.get("amount") != null ? (BigDecimal) map.get("amount") : BigDecimal.ZERO);
            return vo;
        }).collect(Collectors.toList());
    }
}